import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { Subject, Subscription } from 'rxjs';
import { ApesMessageService } from '@shared/apes/message';
import { debounceTime } from 'rxjs/operators';
import { AssemblyDrawingViewService } from '@core/services/assemblyDrawing/assemblyDrawing.view.service';
import { AssemblyDrawingService } from '@core/services/assemblyDrawing/assemblyDrawing.service';
import { deepClone } from '../../../../utils/utils';

@Component({
  selector: 'cad-level-list',
  templateUrl: './cad-level-list.component.html',
  styleUrls: ['./cad-level-list.component.scss'],
})
export class CadLevelListComponent implements OnInit, OnDestroy {

  private selectSubgroup$ = new Subject();

  private subscription: Subscription;
  private selectSubscription: Subscription;
  private lastSubscription: Subscription;
  private nextSubscription: Subscription;

  private currentActive = 0;

  baseData: any = {};
  data: any = {};
  listName: any;
  _isQuery: boolean;
  @Input()
  set isQuery(value: any) {
    this._isQuery = value;
  }

  get isQuery() {
    return this._isQuery;
  }

  constructor(
    private assemblyDrawingViewService: AssemblyDrawingViewService,
    private assemblyDrawingService: AssemblyDrawingService,
    private msgService: ApesMessageService,
  ) {
  }

  ngOnInit(): void {
    this.subscription = this.assemblyDrawingViewService.subgroupChange$.subscribe(data => {
      this.baseData = deepClone(data);
      this.filterData(data);
      this.listName = null;
      this.currentActive = 0;
      this.resolveData(this.data);
    });

    this.selectSubscription = this.selectSubgroup$.pipe(debounceTime(500)).subscribe((value: any) => {
      this.currentActive = value.index;
      // console.log('当前选中的子组数据', value.item);
      this.assemblyDrawingService.selectSubgroup$.next(value.item);
    });

    this.lastSubscription = this.assemblyDrawingService.lastSubgroup$.subscribe(() => {
      let nextIndex = this.currentActive - 1;
      if (nextIndex < 0) {
        this.assemblyDrawingViewService.partsListLoadingChange$.next(false);
        this.msgService.warning('没有上一组');
        // return
      } else {
        this.handleClick(this.data[nextIndex], nextIndex);
      }
    });

    this.nextSubscription = this.assemblyDrawingService.nextSubgroup$.subscribe(() => {
      let nextIndex = this.currentActive + 1;
      if (nextIndex == this.data.length || this.data.length == 0) {
        this.msgService.warning('没有下一组');
        this.assemblyDrawingViewService.partsListLoadingChange$.next(false);
        // return
      } else {
        this.handleClick(this.data[nextIndex], nextIndex);
      }
    });
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
    this.selectSubscription.unsubscribe();
    this.lastSubscription.unsubscribe();
    this.nextSubscription.unsubscribe();
  }

  handleClick(item, index) {
    // 限制重复点击
    this.selectSubgroup$.next({ index, item });
  }

  filterData(data) {
    let filter = [];
    if (data && data.length > 0) {
      data.forEach((res) => {
        if (res['belongTo'] == true || res['isBelongTo'] == true) {
          filter.push(res);
        }
      });
    } else {
      filter = data;
    }
    this.data = filter;
  }

  filterName(value) {
    let name = '';
    if (value) {
      name = value.replace(/\$\$/g, '\r\n');
    }
    return name;
  }

  resolveData(data) {
    if (data && data.length > 0) {
      // let array = [...data,...data];
      let array = data;
      for (let i = 0, len = array.length; i < len; i++) {
        let imageUrls = array[i].imageUrl ? array[i].imageUrl.split(',') : [];
        // imageUrls = imageUrls.map( str => `${this.url}${array[i].cadVersion}/${str}`);
        array[i].imageUrls = imageUrls;
      }
      // this.data = array;
    }
  }

  checkImg(item) {
    let check = false;
    if (item && item.imageUrls && item.imageUrls[0]) {
      let src = item.imageUrls[0].toLowerCase();
      //存在图片
      let exp = ['.jpg', '.jpeg', '.gif', '.bmp', '.png'];
      exp.forEach((e) => {
        if (src.indexOf(e) > -1) {
          check = true;
        }
      });

    }
    return check;
  }

  searchName(param) {
    let value = param.target.value.toUpperCase();
    let list;
    this.data = [];
    if (value) {
      list = this.filtrationData(this.baseData, value);
    } else {
      list = deepClone(this.baseData);
    }
    this.filterData(list);
    this.resolveData(this.data);
  }

  filtrationData(original, keyword) {
    const arr = [];
    for (let item of original) {
      if (item.hasOwnProperty('imageSN') && item['imageSN'].match(keyword) !== null) {
        arr.push(item);
      } else if (item['code'].match(keyword) !== null || item['name'].match(keyword) !== null) {
        arr.push(item);
      }
    }
    return arr;
  }

  clearSearchName() {
    this.listName = null;
    let list = deepClone(this.baseData);
    this.filterData(list);
    this.resolveData(this.data);
  };

}
